package com.pospi.pai.yunpos.vip;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.kyleduo.switchbutton.SwitchButton;
import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.params.ProgressParams;
import com.pospi.callbacklistener.HttpCallBackListener;
import com.pospi.dto.VipBeen;
import com.pospi.http.HttpConnection;
import com.pospi.pai.yunpos.R;
import com.pospi.pai.yunpos.base.Base2Activity;
import com.pospi.pai.yunpos.login.Constant;
import com.pospi.util.GetData;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class VIPRegisterActivity extends Base2Activity implements OnCheckedChangeListener {

    @Bind(R.id.et_vip_name)
    EditText etVipName;
    @Bind(R.id.et_vip_phone)
    EditText etVipPhone;
    @Bind(R.id.tv_vip_birth)
    TextView tvVipBirth;
//    @Bind(R.id.tv_vip_sex)
//    TextView tvVipSex;
    @Bind(R.id.tv_vip_email)
    EditText tvVipEmail;
    @Bind(R.id.tv_vip_address)
    EditText tvVipAddress;
    @Bind(R.id.sb_msg)
    SwitchButton sbMsg;
    @Bind(R.id.tv_vip_sfz)
    EditText tv_vip_sfz;
    @Bind(R.id.tv_vip_pass)
    EditText tv_vip_pass;
    @Bind(R.id.tv_vip_cat)
    TextView tv_vip_cat;
//    @Bind(R.id.sb_leaflet)
//    SwitchButton sbLeaflet;
    @Bind(R.id.et_vip_num)
    TextView et_vip_num;
    @Bind(R.id.btn_sure)
    TextView btnSure;
    private final String TAG = "VIPRegisterActivity.tag";
    private List<VipType> types = new ArrayList<>();
    private List<String> mStrings = new ArrayList<>();
    private String typeid;
    private String ischoose = "0";
    private VipBeen vipBeen;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vipregist);
        setTitle("会员注册");
        ButterKnife.bind(this);
        vipBeen = (VipBeen) getIntent().getSerializableExtra("data");
        if (vipBeen != null) {
            setTitle("会员修改");
            etVipName.setText(vipBeen.getName());
            etVipPhone.setText(vipBeen.getTel());
            btnSure.setText("修改");
        }

        getviptype();
        tvVipBirth.setText(GetData.getYYMMDDTime());

        sbMsg.setOnCheckedChangeListener(this);
    }

    @OnClick({R.id.tv_vip_birth, R.id.btn_sure ,R.id.tv_vip_cat,R.id.zfpt_return})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.zfpt_return:
                finish();
                break;
            case R.id.tv_vip_cat:
                mStrings.clear();
                for (VipType type : types) {
                    mStrings.add(type.getName());
                }
                creatDialog(mStrings);

                break;
            case R.id.tv_vip_birth:
                showDate(tvVipBirth);
//                long mixYears = 80L * 365 * 1000 * 60 * 60 * 24L;
//                TimePickerDialog dialogYearMonthDay = new TimePickerDialog.Builder()
//                        .setType(Type.YEAR_MONTH_DAY)
//                        .setTitleStringId("选择日期")
//                        .setWheelItemTextSize(16)
//                        .setThemeColor(R.color.title)
//                        .setMaxMillseconds(System.currentTimeMillis())
//                        .setMinMillseconds(System.currentTimeMillis() - mixYears)
//                        .setCallBack(new OnDateSetListener() {
//                            @Override
//                            public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
//                                Date date = new Date(millseconds);
//                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//                                String time = format.format(date);
//                                tvVipBirth.setText(time);
//                            }
//                        })
//                        .build();
//                dialogYearMonthDay.show(getSupportFragmentManager(), "YEAR_MONTH_DAY");
                break;
//            case R.id.tv_vip_sex:
//                creatSexDialog();
//                break;
//            case R.id.btn_cancle:
//                finish();
//                break;
            case R.id.btn_sure:
                if (et_vip_num.getText().toString().isEmpty() || etVipPhone.getText().toString().isEmpty() || etVipName.getText().toString().isEmpty()) {
                    Toast.makeText(this, "必填项不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                register();
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.sb_msg://是否启用密码
                if (isChecked) {
                    ischoose = "1";
                } else {
                    ischoose = "0";
                }
                break;

        }
    }

    private String[] sexs = new String[]{"男","女"};
    private void creatSexDialog() {

        new CircleDialog.Builder(this)
                .setItems(sexs, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                        tvVipSex.setText(sexs[i]);
                    }
                })
                .setGravity(Gravity.CENTER)
                .show();
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    close();
                    new CircleDialog.Builder()
                            .setTitle("提示")
                            .setText("注册成功")
                            .setPositive("确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    VIPRegisterActivity.this.finish();
                                }
                            })
                            .show(getSupportFragmentManager());
                    break;
                case 2:
                    close();
                    Toast.makeText(VIPRegisterActivity.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    close();
                    Toast.makeText(VIPRegisterActivity.this, "手机号已经被注册", Toast.LENGTH_SHORT).show();
                    break;
                case 4:

                    break;
            }

        }
    };
    private void creatDialog(final List<String> strings) {

        new CircleDialog.Builder(this)
                .setItems(strings, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        tv_vip_cat.setText(strings.get(i));
                        typeid = types.get(i).getId();
                    }
                })
                .setGravity(Gravity.CENTER)
                .setWidth(0.5f)
                .show();
    }

    private void register(){
        showDialog();
        Map<String,String> params = new HashMap<>();
        params.put("model", "vip.Vvip");
        params.put("fun", "save");//find   filter
        params.put("table", "vip_info");
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));


        JSONObject object = new JSONObject();
        try {
            if (vipBeen != null) {
                object.put("id", vipBeen.getId());
            } else {
                object.put("id", "0");
            }

            object.put("num", et_vip_num.getText().toString().trim());
            object.put("name", etVipName.getText().toString().trim());
            object.put("channel", "线下门店");
            object.put("sex", "");
            object.put("typeid", typeid);

            object.put("status", "1");
            object.put("marketid", SPHelper.getInstance().getString(Constant.STORE_ID));
            object.put("birthday", tvVipBirth.getText().toString());
            object.put("pwd", tv_vip_pass.getText().toString().trim());
            object.put("tel", etVipPhone.getText().toString().trim());

            object.put("sfzh", tv_vip_sfz.getText().toString().trim());
            object.put("addr", tvVipAddress.getText().toString().trim());
            object.put("email", tvVipEmail.getText().toString().trim());
            object.put("qq", "");
            object.put("wx", "");

            object.put("dw", "");
            object.put("zy", "");
            object.put("sr", "");
            object.put("personid", "");
            object.put("xfcs", "");


            object.put("xfje", "");
            object.put("jfye", "");
            object.put("mzye", "");
            object.put("lastxfrq", "");
            object.put("lastmemo", "");
            object.put("memo", "");
            object.put("ispwd", ischoose);//0不启用 ，1启用

        } catch (JSONException e) {
            e.printStackTrace();
        }

        params.put("pds", object.toString());
        new HttpConnection().postNet(params, new HttpCallBackListener() {
            @Override
            public void CallBack(String Response) {
                Log.i(TAG, Response);
                try {
                    final JSONObject object = new JSONObject(Response);


                    if (!object.getString("errCode").equals("100")) {
                        Message message = Message.obtain();
                        message.what = 2;
                        message.obj = object.getString("errMsg");
                        handler.sendMessage(message);
                    } else {
                        Message message = Message.obtain();
                        message.what = 1;
                        handler.sendMessage(message);

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });


    }
    private void getviptype(){
        Map<String,String> params = new HashMap<>();
        params.put("model", "vip.Vvip");
        params.put("fun", "getviptype");
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        new HttpConnection().postNet(params, new HttpCallBackListener() {
            @Override
            public void CallBack(String Response) {
                Log.i(TAG, Response);


                try {
                    final JSONObject object = new JSONObject(Response);
                    if (object.getString("errCode").equals("105")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Toast.makeText(VIPRegisterActivity.this, object.getString("errMsg"), Toast.LENGTH_SHORT).show();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                    types = new Gson().fromJson(object.getJSONArray("result").toString(), new TypeToken<List<VipType>>() {
                    }.getType());

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });


    }
    private DialogFragment dialog;
    private void showDialog(){
        dialog = new CircleDialog.Builder()
                .setProgressText("加载中...")
                .setProgressStyle(ProgressParams.STYLE_SPINNER)
                .show(getSupportFragmentManager());
    }
    private void close(){
        dialog.dismiss();
    }
    private void showDate(final TextView tv) {
        final Calendar c = Calendar.getInstance();
        DatePickerDialog dialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                c.set(year, monthOfYear, dayOfMonth);
                tv.setText(DateFormat.format("yyyy-MM-dd", c));
            }
        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }
}
